package com.jswdwsx.esign.protocol

import com.jswdwsx.esign.commom.ResEnum
import com.jswdwsx.esign.exception.EsignApiCallException
import com.jswdwsx.esign.exception.EsignBusinessException
import retrofit2.Call
import retrofit2.CallAdapter
import retrofit2.Retrofit
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

class EsignCallAdapterFactory private constructor() : CallAdapter.Factory() {

    companion object {
        private val INSTANCE = EsignCallAdapterFactory()

        fun create(): EsignCallAdapterFactory {
            return INSTANCE
        }
    }

    override fun get(returnType: Type, annotations: Array<Annotation>, retrofit: Retrofit): CallAdapter<*, *>? {
        if (getRawType(returnType) != EsignResp::class.java) {
            return null
        }
        if (returnType !is ParameterizedType) {
            throw IllegalStateException("EsignResp return type must be parameterized" + " as EsignResp<Foo> or EsignResp<? extends Foo>")
        }
        return EsignCallAdapter<Any>(returnType)
    }
}

class EsignCallAdapter<R>(private val responseType: Type) : CallAdapter<R, R> {
    override fun responseType() = responseType
    override fun adapt(call: Call<R>): R {

        val response = call.execute()
        if (response.isSuccessful) {
            val esignResp = response.body()
            if (esignResp != null) {
                return esignResp
            } else {
                throw EsignApiCallException(ResEnum.CallEsignApiRespError)
            }
        } else {
            throw EsignApiCallException(ResEnum.CallEsignApiFail,"url:${call.request().url},httpCode:${response.code()},message:${response.message()}")
        }
    }
}
